<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CmtVolunteerApplyApi } from '#/api/cmt/person/volunteerApply';

import { ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { ElMessage, ElTag } from 'element-plus';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteVolunteerApply,
  deleteVolunteerApplyList,
  exportVolunteerApply,
  getVolunteerApplyPage,
} from '#/api/cmt/person/volunteerApply';
import { $t } from '#/locales';

import {
  APPLY_TYPE_OPTIONS,
  AUDIT_STATUS_OPTIONS,
  GENDER_OPTIONS,
  useGridColumns,
  useGridFormSchema,
} from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 创建志愿者/师资申请 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 编辑志愿者/师资申请 */
function handleEdit(row: CmtVolunteerApplyApi.VolunteerApply) {
  formModalApi.setData(row).open();
}

/** 删除志愿者/师资申请 */
async function handleDelete(row: CmtVolunteerApplyApi.VolunteerApply) {
  try {
    await deleteVolunteerApply(row.id!);
    ElMessage.success($t('ui.actionMessage.deleteSuccess'));
    handleRefresh();
  } catch (error) {
    console.error(error);
  }
}

/** 批量删除志愿者/师资申请 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  try {
    await deleteVolunteerApplyList(checkedIds.value);
    checkedIds.value = [];
    ElMessage.success($t('ui.actionMessage.deleteSuccess'));
    handleRefresh();
  } catch (error) {
    console.error(error);
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: CmtVolunteerApplyApi.VolunteerApply[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportVolunteerApply(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '志愿者师资申请.xls', source: data });
}

/** 获取申请类型标签 */
function getApplyTypeLabel(type: number) {
  return APPLY_TYPE_OPTIONS.find((item) => item.value === type)?.label || '';
}

/** 获取性别标签 */
function getGenderLabel(gender: number) {
  return GENDER_OPTIONS.find((item) => item.value === gender)?.label || '';
}

/** 获取审核状态标签 */
function getAuditStatusLabel(status: number) {
  return AUDIT_STATUS_OPTIONS.find((item) => item.value === status)?.label || '';
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    collapsed: true,
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getVolunteerApplyPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<CmtVolunteerApplyApi.VolunteerApply>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <Grid table-title="志愿者/师资申请列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['申请']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['cmt:person-volunteer-apply:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['cmt:person-volunteer-apply:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['cmt:person-volunteer-apply:delete'],
              disabled: isEmpty(checkedIds),
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>
      <template #applyType="{ row }">
        <ElTag :type="row.applyType === 1 ? 'primary' : 'success'">
          {{ getApplyTypeLabel(row.applyType) }}
        </ElTag>
      </template>
      <template #gender="{ row }">
        <span>{{ getGenderLabel(row.gender) }}</span>
      </template>
      <template #auditStatus="{ row }">
        <ElTag
          :type="
            row.auditStatus === 0
              ? 'warning'
              : row.auditStatus === 1
                ? 'success'
                : 'danger'
          "
        >
          {{ getAuditStatusLabel(row.auditStatus) }}
        </ElTag>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'primary',
              link: true,
              icon: ACTION_ICON.EDIT,
              auth: ['cmt:person-volunteer-apply:update'],
              onClick: handleEdit.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: $t('common.delete'),
              type: 'primary',
              link: true,
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['cmt:person-volunteer-apply:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
